package util;

import java.util.Arrays;

/**
 * @author Karl
 * @Date 2023/1/3 - 14:39
 */
public class MyArrays {
    public static int[] kmpNext(byte[] dest){
        int[] next = new int[dest.length];
        next[0] = 0;

        for(int i = 1,j = 0; i < dest.length; i++){
            while(j > 0 && dest[j] != dest[i]){
                j = next[j - 1];
            }
            if(dest[i] == dest[j]){
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static int kmp(byte[] src, byte[] dest ,int off ,int len){
        if(dest.length>len||src.length<len) return -1;
        //1.首先计算出部分匹配表
        int end = Math.min(off+len,src.length);
        int[] next = kmpNext(dest);
        //2.查找匹配位置
        for(int i = off, j = 0; i < end; i++){
            while(j > 0 && src[i] != dest[j]){
                j = next[j-1];
            }
            if(src[i] == dest[j]){
                j++;
            }
            if(j == dest.length){
                return i-j+1;
            }
        }
        return -1;
    }

    public static int kmp(byte[] str, byte[] dest){
        return kmp(str,dest,0,str.length);
    }

    /**
     * 将数组从off开始移到第一位去
     * @param bytes 数组
     * @param off 偏移量
     */
    public static void moveToHead(byte[] bytes,int off){
        for (int i = 0,j=off; j < bytes.length; i++,j++) {
            bytes[i] = bytes[j];
        }
    }

    /**
     * 将数组从off开始移到第一位去
     * @param bytes 数组
     * @param begin 偏移量
     */
    public static void moveToHead(byte[] bytes,int begin,int end){
        for (int i = 0,j=begin; j < Math.min(bytes.length,end); i++,j++) {
            bytes[i] = bytes[j];
            bytes[j] = 0;
        }
    }
}
